package com.shwread.httpsdk.http.download;

import android.content.Context;

import com.shwread.httpsdk.http.callback.IoTaskProgress;
import com.shwread.httpsdk.http.callback.IoTaskProgress.HttpType;
import com.shwread.httpsdk.util.NetUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;

import base.tina.core.task.infc.ITaskProgress.TaskProgressType;
import logic.util.SDcardUtil;


/**
 * @Title: DownloadTTAction.java
 * @Package com.surfingread.httpsdk.http.face.self
 * @Description: TODO(添加描述)
 * @author 刘章
 * @date 2014年2月18日 下午8:32:37
 */
public class DownloadForProgressAction
        extends
        Thread
{
	private HttpURLConnection httpConnection;
	private File              file;
	private FileOutputStream  fileOutputStream;
	private InputStream       inStream;
	private int               downsize;
	private int               filesize;
	private boolean           over      = false;
	
	final Context             context;
	final String              url;
	final String              localpath;
	final IoTaskProgress      progress;
	private long              startTime = 0;
	private long              currTime  = 0;
	
	public DownloadForProgressAction(Context context, String url, String localpath, IoTaskProgress progress) {
		this.context = context;
		this.url = url;
		this.localpath = localpath;
		this.progress = progress;
	}
	
	@Override
	public void run() {
		try
		{
			String proxyUrl = NetUtil.getNetworkProxyUrl(context);
			if (proxyUrl != null && proxyUrl.length() > 0)
			{
				if (NetUtil.isNeedSetProxyForNetRequest()) //三星N719变态机子
				httpConnection = (HttpURLConnection) new URL(url).openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl, NetUtil.getNetworkProxyPort())));
				else httpConnection = (HttpURLConnection) new URL(url).openConnection();
			}
			else
			{
				URL infoUrl = new URL(url);
				httpConnection = (HttpURLConnection) infoUrl.openConnection();
				//如下3行代码,兼容QAS引起的速度变慢问题,由于QAS也是使用HttpURLConnection,这边需要调整如下参数
				System.getProperties().remove("proxySet");
				System.getProperties().remove("http.proxyHost");
				System.getProperties().remove("http.proxyPort");
			}
			
			/*
			 * httpConnection = (HttpURLConnection) new
			 * URL(url).openConnection();
			 * Properties properties = System.getProperties();
			 * properties.setProperty("proxySet", "true");
			 * properties.setProperty("http.proxyHost",ProxyConsts.Proxy_ip);
			 * properties.setProperty("http.proxyPort",String.valueOf(ProxyConsts
			 * .Proxy_port));
			 * httpConnection.setRequestProperty("ab_pid",
			 * Base64.encode(ProxyConsts.appId, "UTF-8"));
			 * httpConnection.setRequestProperty("ab_uid",
			 * Base64.encode(ProxyConsts.userId, "UTF-8"));
			 */
			
			httpConnection.setRequestMethod("GET");
			httpConnection.setConnectTimeout(20000);//连接20s超时
			httpConnection.setReadTimeout(30000);//读取数据30s超时
			httpConnection.setDoInput(true);// 允许输入
			httpConnection.setDoOutput(false);// 允许输出
			httpConnection.setUseCaches(false);// 不使用Cache
			httpConnection.setRequestProperty("Connection", "Keep-Alive");
			httpConnection.setRequestProperty("Charset", "UTF-8");
			
			int responseCode = httpConnection.getResponseCode();
			//#debug
			System.out.println("-------服务器响应--" + responseCode + "-----");
			if (responseCode == 200)
			{
				filesize = httpConnection.getContentLength();
				progress.createProgress(HttpType.Download, TaskProgressType.horizontal, filesize);
				file = new File(localpath);
				if (file.exists())
				{
					file.delete();
				}
				file.createNewFile();
				fileOutputStream = new FileOutputStream(file);
				inStream = httpConnection.getInputStream();
				//System.out.println("-------输入流--" + inStream + "-----");
				byte[] buffer = new byte[1024];
				int length = 0;
				startTime = System.currentTimeMillis();
				while (SDcardUtil.isSDCARDMounted() && NetUtil.isNetworkConnected(context))
				{
					length = inStream.read(buffer);
					if (length == -1)
					{
						over = true;
						break;
					}
					currTime = System.currentTimeMillis();
					//System.out.println("length=" + length + " " + file.exists());
					if (file.exists())
					{
						fileOutputStream.write(buffer, 0, length);
						downsize += length;
						if ((currTime - startTime > 1000))
						{
							startTime = currTime;
							progress.updateProgress(HttpType.Download, TaskProgressType.percent, downsize, filesize);
						}
						
					}
					else
					{
						break;
					}
					Thread.yield();
				}
				if (over)
				{
					/**
					 * 修改状态为成功
					 */
					progress.finishProgress(HttpType.Download, TaskProgressType.complete);
				}
				else
				{
					file.delete();
					progress.finishProgress(HttpType.Download, TaskProgressType.cancel);
				}
			}
			else
			{
				progress.finishProgress(HttpType.Download, TaskProgressType.error);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			progress.finishProgress(HttpType.Download, TaskProgressType.error);
		}
		finally
		{
			if (fileOutputStream != null)
			{
				try
				{
					fileOutputStream.flush();
					fileOutputStream.close();
					fileOutputStream = null;
				}
				catch (Exception e)
				{
					
				}
			}
			if (file != null)
			{
				file = null;
			}
			if (inStream != null)
			{
				try
				{
					inStream.close();
					inStream = null;
				}
				catch (Exception e)
				{
					
				}
			}
			if (httpConnection != null)
			{
				httpConnection.disconnect();
				httpConnection = null;
			}
		}
	}
	
}
